package com.glsc.ngateway.common.oc.config;

import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Properties;

@Configuration
public class OcDatasourceConfig {

    @Resource(name = OcDataSourceDefConfig.DS_MYSQL_OC)
    private DataSource datasourceMysqlOc;

    /**
     * 多数据源，自定义mysql/oracle的连接属性
     */
    @Bean(name = "entityManagerFactoryMysqlOc")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryMysqlOc(EntityManagerFactoryBuilder builder) {
        LocalContainerEntityManagerFactoryBean emf = builder
                .dataSource(datasourceMysqlOc)
                .packages("com.glsc.ngateway.common.oc.domain") //设置实体类所在位置
                .persistenceUnit("mysqlOcPersistenceUnit")
                .build();
        Properties properties = new Properties();
        //方言
        properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL55Dialect");
        //不需要自动创建、更新、验证数据库表结构
        properties.setProperty("hibernate.hbm2ddl.auto", "none");
        properties.setProperty("hibernate.physical_naming_strategy", "org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl");
        //输出SQL
        properties.setProperty("hibernate.show_sql", "true");
        properties.setProperty("hibernate.format_sql", "true");
        //懒加载
        properties.setProperty("hibernate.enable_lazy_load_no_trans", "true");
        emf.setJpaProperties(properties);
        return emf;
    }

    @Bean(name = "entityManagerMysqlOc")
    public EntityManager entityManagerMysqlOc(EntityManagerFactoryBuilder builder) {
        return entityManagerFactoryMysqlOc(builder).getObject().createEntityManager();
    }

    @Bean(name = "transactionManagerMysqlOc")
    public PlatformTransactionManager transactionManagerMysqlOc(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryMysqlOc(builder).getObject());
    }

}
